﻿using System.Collections.ObjectModel;
using System.Windows;
using WPFServices.Commands;
using WPFServices.Models.AI;
using WPFServices.Services.AI;

namespace WPFServices.ViewModels.AI
{
    public class ChatViewModel : BaseViewModel, IDisposable
    {
        private readonly ChatService _chatService;
        private string _inputMessage = string.Empty;
        private bool _isSending = false;
        private bool _useStreamMode = true;
        private CancellationTokenSource _cancellationTokenSource;
        private string _conversationId = string.Empty;

        public ChatViewModel()
        {
            _chatService = new ChatService();
            Messages = new ObservableCollection<ChatMessage>();

            SendCommand = new RelayCommand(async _ => await SendMessageAsync(), _ => CanSendMessage());
            ClearCommand = new RelayCommand(_ => ClearMessages());
            StopCommand = new RelayCommand(_ => StopGeneration(), _ => IsSending);
            ToggleModeCommand = new RelayCommand(_ => ToggleMode());

            // 添加欢迎消息
            AddWelcomeMessage();
        }

        #region 属性
        public ObservableCollection<ChatMessage> Messages { get; }

        public string InputMessage
        {
            get => _inputMessage;
            set => SetProperty(ref _inputMessage, value);
        }

        public bool IsSending
        {
            get => _isSending;
            set => SetProperty(ref _isSending, value);
        }

        public bool UseStreamMode
        {
            get => _useStreamMode;
            set => SetProperty(ref _useStreamMode, value);
        }

        public string ModeText => UseStreamMode ? "流式模式" : "回调模式";
        #endregion

        #region 命令
        public RelayCommand SendCommand { get; }
        public RelayCommand ClearCommand { get; }
        public RelayCommand StopCommand { get; }
        public RelayCommand ToggleModeCommand { get; }
        #endregion

        #region 方法
        private bool CanSendMessage()
        {
            return !string.IsNullOrWhiteSpace(InputMessage) && !IsSending;
        }

        private async Task SendMessageAsync()
        {
            if (string.IsNullOrWhiteSpace(InputMessage)) return;

            var userMessage = InputMessage.Trim();
            InputMessage = string.Empty;

            // 添加用户消息
            var userChatMessage = new ChatMessage
            {
                Type = MessageType.User,
                Content = userMessage
            };

            Application.Current.Dispatcher.Invoke(() => Messages.Add(userChatMessage));

            // 创建请求
            var request = new AiRequestDto
            {
                Message = userMessage,
                UserId = "user_test001",
                ConversationId = _conversationId
            };

            if (UseStreamMode)
            {
                await SendStreamMessageAsync(request);
            }
            else
            {
                await SendCallbackMessageAsync(request);
            }
        }

        private async Task SendStreamMessageAsync(AiRequestDto request)
        {
            // 创建AI响应消息
            var aiMessage = new ChatMessage
            {
                Type = MessageType.Assistant,
                Content = string.Empty,
                IsStreaming = true
            };

            Application.Current.Dispatcher.Invoke(() => Messages.Add(aiMessage));

            try
            {
                IsSending = true;
                _cancellationTokenSource?.Cancel();
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = new CancellationTokenSource();

                await _chatService.SendStreamChatAsync(request, chunk =>
                {
                    if (_cancellationTokenSource?.Token.IsCancellationRequested == true)
                        return;

                    Application.Current.Dispatcher.BeginInvoke(() =>
                    {
                        switch (chunk.Type?.ToLower())
                        {
                            case "content":
                                // 解码Unicode字符
                                var decodedContent = System.Text.RegularExpressions.Regex.Unescape(chunk.Content);
                                aiMessage.Content += decodedContent;
                                break;

                            case "messagecompleted":
                                // 消息完成，但继续等待Done
                                break;

                            case "done":
                                aiMessage.IsStreaming = false;
                                if (!string.IsNullOrEmpty(chunk.ConversationId))
                                    _conversationId = chunk.ConversationId;
                                break;

                            case "error":
                                aiMessage.Content = $"❌ 错误: {chunk.Content}";
                                aiMessage.IsStreaming = false;
                                break;
                        }
                    });
                }, _cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    aiMessage.Content = $"❌ 发送失败: {ex.Message}";
                    aiMessage.IsStreaming = false;
                });
            }
            finally
            {
                IsSending = false;
            }
        }

        private async Task SendCallbackMessageAsync(AiRequestDto request)
        {
            // 创建AI响应消息
            var aiMessage = new ChatMessage
            {
                Type = MessageType.Assistant,
                Content = "🤔 正在思考...",
                IsStreaming = true
            };

            Application.Current.Dispatcher.Invoke(() => Messages.Add(aiMessage));

            try
            {
                IsSending = true;
                _cancellationTokenSource?.Cancel();
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = new CancellationTokenSource();

                var response = await _chatService.SendCallbackChatAsync(request, _cancellationTokenSource.Token);

                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (response.Success)
                    {
                        aiMessage.Content = response.Response;
                        if (!string.IsNullOrEmpty(response.ConversationId))
                            _conversationId = response.ConversationId;
                    }
                    else
                    {
                        aiMessage.Content = $"❌ 错误: {response.Error}";
                    }
                    aiMessage.IsStreaming = false;
                });
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    aiMessage.Content = $"❌ 发送失败: {ex.Message}";
                    aiMessage.IsStreaming = false;
                });
            }
            finally
            {
                IsSending = false;
            }
        }

        private void StopGeneration()
        {
            _cancellationTokenSource?.Cancel();
        }

        private void ClearMessages()
        {
            Messages.Clear();
            AddWelcomeMessage();
            _conversationId = string.Empty; // 清空会话ID
        }

        private void ToggleMode()
        {
            UseStreamMode = !UseStreamMode;
            OnPropertyChanged(nameof(ModeText));
        }

        private void AddWelcomeMessage()
        {
            var welcomeMessage = new ChatMessage
            {
                Type = MessageType.Assistant,
                Content = "👋 你好！我是小困鱼，你的MES系统智能助手。有什么生产相关的信息需要查询或帮助，随时告诉我哦~"
            };
            Messages.Add(welcomeMessage);
        }
        #endregion

        public void Dispose()
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _chatService?.Dispose();
        }
    }
}